package com.uzai.console.service.jd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowQueryResult;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.jd.jdtokenapi.*;
import com.uzai.console.entity.JdToken;
import com.uzai.console.entity.JdTokenApi;
import com.uzai.console.entity.Merchant;
import com.uzai.console.mapper.JdTokenApiMapper;
import com.uzai.console.mapper.JdTokenMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.jd.JdTokenApiService;
import com.uzai.console.vo.jd.jdtokenapi.JdTokenApiInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 运营商基本配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class JdTokenApiServiceImpl implements JdTokenApiService {


    Logger logger = LoggerFactory.getLogger(JdTokenApiServiceImpl.class);

    @Autowired
    private JdTokenApiMapper jdTokenApiMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询京东联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiQuery
     * @return null
     */
    public Page<JdTokenApiInfoVo> findJdTokenApiList(JdTokenApiQuery jdTokenApiQuery){
        //新建返回到页面的LIST对象
        List<JdTokenApiInfoVo> jdTokenApiInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<JdTokenApi> page = new Page<>();
        jdTokenApiQuery.convert(page);
        ArrayList<JdTokenApi> jdOrderList =  jdTokenApiMapper.findByList(page, jdTokenApiQuery);
        if(jdOrderList != null && jdOrderList.size() > 0){
            for (JdTokenApi jdTokenApi : jdOrderList){
                JdTokenApiInfoVo jdTokenApiInfoVo = new JdTokenApiInfoVo();
                BeanUtils.copyProperties(jdTokenApi, jdTokenApiInfoVo);
                jdTokenApiInfoVoList.add(jdTokenApiInfoVo);
            }
        }

        //返回到页面分页对象
        Page<JdTokenApiInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(jdTokenApiInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询京东联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiIdDto
     * @return null
     */
    public JdTokenApiInfoVo findJdTokenApiInfo(JdTokenApiIdDto jdTokenApiIdDto){

        if(jdTokenApiIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        JdTokenApi jdTokenApi = jdTokenApiMapper.selectById(jdTokenApiIdDto.getId(), jdTokenApiIdDto.getMerId());
        if(jdTokenApi == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该京东联盟账号不存在");
        }

        //返回页面对象
        JdTokenApiInfoVo jdTokenApiInfoVo = new JdTokenApiInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(jdTokenApi, jdTokenApiInfoVo);

        return jdTokenApiInfoVo;
    }

    /**
     * 添加京东联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiInfoDto
     * @return null
     */
    public void addJdTokenApi(JdTokenApiInfoDto jdTokenApiInfoDto){

        JdTokenApi jdTokenApi = new JdTokenApi();

        BeanUtils.copyProperties(jdTokenApiInfoDto, jdTokenApi);

//        if(jdTokenApiInfoDto.getType() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
//        }

        if(StringUtils.isBlank(jdTokenApiInfoDto.getUnionId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "京东联盟id不能为空");
        }
        jdTokenApi.setUnionId(jdTokenApiInfoDto.getUnionId());

        if(StringUtils.isBlank(jdTokenApiInfoDto.getAuthKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "授权key不能为空");
        }
        jdTokenApi.setAuthKey(jdTokenApiInfoDto.getAuthKey());

        //先判断该授权是否在京东联盟里使用过
        JdToken jdToken = jdTokenMapper.selectByUnionId(jdTokenApiInfoDto.getUnionId());
        if(jdToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "授权的账号在联盟授权列表不存在！");
        }

        if(jdToken.getMerId().longValue() != jdTokenApiInfoDto.getMerId().longValue()){
            Merchant merchant1 = merchantMapper.selectById(jdToken.getMerId());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.ALIMM_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant1.getMobile())));
        }

        JdTokenApi jdTokenApi_old = jdTokenApiMapper.selectByUnionId(jdTokenApiInfoDto.getUnionId());
        if(jdTokenApi_old != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟id已经存在");
        }

        jdTokenApi.setId(IdWorker.getId());
        Integer now = DateUtil.getNowTime();
        jdTokenApi.setCreateTime(now);
        jdTokenApi.setUpdateTime(now);
        jdTokenApi.setType(0); //京东
        jdTokenApiMapper.insertSelective(jdTokenApi);
    }

    /**
     * 修改京东联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiInfoDto
     * @return null
     */
    public void updateJdTokenApi(JdTokenApiInfoDto jdTokenApiInfoDto){

        if(jdTokenApiInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        JdTokenApi jdTokenApi = jdTokenApiMapper.selectById(jdTokenApiInfoDto.getId(), jdTokenApiInfoDto.getMerId());

        if(jdTokenApi == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟不存在");
        }

        Integer now = DateUtil.getNowTime();
        jdTokenApi.setRemark(jdTokenApiInfoDto.getRemark());
        jdTokenApi.setAuthKey(jdTokenApiInfoDto.getAuthKey());
        //jdTokenApi.setUnionId(jdTokenApiInfoDto.getUnionId());
        jdTokenApi.setUpdateTime(now);
        jdTokenApiMapper.updateByIdSelective(jdTokenApi);
    }

    /**
     * 添加京拥联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiInfoDto
     * @return null
     */
    public void addJyToken(JdTokenApiInfoDto jdTokenApiInfoDto){

        if(StringUtils.isBlank(jdTokenApiInfoDto.getAuthKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "渠道编号不能为空");
        }
//
//        if(jdTokenApiInfoDto.getType() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
//        }

        JdTokenApi jdTokenApi = new JdTokenApi();
        BeanUtils.copyProperties(jdTokenApiInfoDto,jdTokenApi);
        jdTokenApi.setId(IdWorker.getId());
        jdTokenApi.setType(1);
        Integer now = DateUtil.getNowTime();
        jdTokenApi.setCreateTime(now);
        jdTokenApi.setUpdateTime(now);

        jdTokenApiMapper.insertSelective(jdTokenApi);
    }


    /**
     * 修改京拥联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiInfoDto
     * @return null
     */
    public void updateJyToken(JdTokenApiInfoDto jdTokenApiInfoDto){

        if(jdTokenApiInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        if(StringUtils.isBlank(jdTokenApiInfoDto.getUnionId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主体名称不能为空");
        }


        JdTokenApi jdTokenApi = jdTokenApiMapper.selectById(jdTokenApiInfoDto.getId(), jdTokenApiInfoDto.getMerId());

        jdTokenApi.setUnionId(jdTokenApiInfoDto.getUnionId());
        Integer now = DateUtil.getNowTime();
        jdTokenApi.setUpdateTime(now);
        jdTokenApiMapper.updateByIdSelective(jdTokenApi);
    }

    /**
     * 删除联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiIdDto
     * @return null
     */
    public void deleteToken(JdTokenApiIdDto jdTokenApiIdDto){
        if(jdTokenApiIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }
        jdTokenApiMapper.deleteById(jdTokenApiIdDto.getId(), jdTokenApiIdDto.getMerId());

    }

//    /**
//     * 创建推广位
//     * @author liuqi
//     * @date 2021/8/13 11:38
//     * @param jdTokenApiCretePidDto
//     * @return null
//     */
//    public JdTokenApiCreatePidVo createPid(JdTokenApiCretePidDto jdTokenApiCretePidDto){
//
//        if(jdTokenApiCretePidDto.getId() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
//        }
//
//        if (jdTokenApiCretePidDto.getPidCount() == null || jdTokenApiCretePidDto.getPidCount() < 1 ){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
//        }
//        if (jdTokenApiCretePidDto.getPidCount()>50){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "一次最多50个推广位");
//        }
//
//        JdTokenApi jt = jdTokenApiMapper.selectById(jdTokenApiCretePidDto.getId(), jdTokenApiCretePidDto.getMerId());
//        if (jt==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该联盟不存在");
//        }
//
//        JdTokenApiCreatePidVo jdTokenApiCreatePidVo = null;
//        List<String> pids = new ArrayList<>();
//        try {
//            JdClient client= new DefaultJdClient(uzaiConsoleSysConfig.getJdServerUrl(),"", uzaiConsoleSysConfig.getJdAppKey(), uzaiConsoleSysConfig.getJdAppsecret());
//            UnionOpenPositionCreateRequest request = new UnionOpenPositionCreateRequest();
//            PositionReq positionReq=new PositionReq();
//            positionReq.setUnionId(Long.parseLong(jt.getUnionId()));
//            positionReq.setKey(jt.getAuthKey());
//            positionReq.setUnionType(1);
//            positionReq.setType(4);
//
//            String[] tgNames = createTgName(jdTokenApiCretePidDto.getPidCount());
//            positionReq.setSpaceNameList(tgNames);
//            request.setPositionReq(positionReq);
//            UnionOpenPositionCreateResponse response=client.execute(request);
//            if (response.getData()==null){
//                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"创建失败，请重试！");
//            }
//            Map<String,String> result = response.getData().getResultList();
//            for (Map.Entry entry:result.entrySet()){
//                pids.add(entry.getValue().toString());
//            }
//
//            jdTokenApiCreatePidVo = new JdTokenApiCreatePidVo();
//            jdTokenApiCreatePidVo.setPids(pids);
//
//        } catch (JdException e) {
//        }
//
//        return jdTokenApiCreatePidVo;
//
//    }
//
//    //随机创立任意数目的随机码
//    private String[] createTgName(int count){
//        RandomString randomString = new RandomString(6);
//        String TG_PREFIX = "yzsoft_";
//        List<String> list = new ArrayList<>();
//        for (int i=0;i<count;i++){
//            String tgName = TG_PREFIX+randomString.nextString();
//            if (list.contains(tgName)){
//                i=i-1;
//                continue;
//            }
//            list.add(tgName);
//        }
//        String[] arr = new String[list.size()];
//        return list.toArray(arr);
//    }
//
//    public Page<PidVo> queryPid(JdTokenApiPidQuery jdTokenApiPidQuery) {
//
//        if(jdTokenApiPidQuery.getId() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
//        }
//
//        JdTokenApi jt = jdTokenApiMapper.selectById(jdTokenApiPidQuery.getId(), jdTokenApiPidQuery.getMerId());
//
//        if (jt==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.PARAM_ERROR);
//        }
//
//        JdClient client=new DefaultJdClient(uzaiConsoleSysConfig.getJdServerUrl(),"", uzaiConsoleSysConfig.getJdAppKey(), uzaiConsoleSysConfig.getJdAppsecret());
//        UnionOpenPositionQueryRequest request=new UnionOpenPositionQueryRequest();
//        Map<String,Object> result = pidList(client, request, jdTokenApiPidQuery.getCurrent(), jdTokenApiPidQuery.getSize(), jt);
//        Page<PidVo> pidVoPage = new Page<>();
//        pidVoPage.setRecords((List<PidVo>) result.get("result"));
//        pidVoPage.setTotal((Integer) result.get("count"));
//        return pidVoPage;
//    }
//
//    //查询京东联盟的推广位列表
//    private Map<String,Object> pidList(JdClient client,UnionOpenPositionQueryRequest request,
//                                       int pageIndex,int pageSize, JdTokenApi jt){
//        Map<String,Object> res = new HashMap<>();
//        try {
//            jd.union.open.position.query.request.PositionReq positionReq=new jd.union.open.position.query.request.PositionReq();
//            positionReq.setUnionId(Long.parseLong(jt.getUnionId()));
//            positionReq.setKey(jt.getAuthKey());
//            positionReq.setUnionType(3);
//            positionReq.setPageIndex(pageIndex);
//            positionReq.setPageSize(pageSize);
//            request.setPositionReq(positionReq);
//            UnionOpenPositionQueryResponse response=client.execute(request);
//            List<PidVo> result = new ArrayList<>();
//            int count = 0;
//            if (response.getData()!=null &&
//                    response.getData().getResult()!=null && response.getData().getResult().length>0){
//                PositionResp[] pr = response.getData().getResult();
//                for (int i=0;i<pr.length;i++){
//                    PidVo pidVo = new PidVo();
//                    pidVo.setId(String.valueOf(pr[i].getId()));
//                    pidVo.setName(pr[i].getSpaceName());
//                    result.add(pidVo);
//                }
//                count = response.getData().getTotal().intValue();
//            }
//            res.put("result",result);
//            res.put("count",count);
//        } catch (JdException e) {
//        }
//        return res;
//    }

    /**
     * 设置PID
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenApiInfoDto
     * @return null
     */
    public void setPid(JdTokenApiInfoDto jdTokenApiInfoDto){
        if(jdTokenApiInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        JdTokenApi jdTokenApi = jdTokenApiMapper.selectById(jdTokenApiInfoDto.getId(), jdTokenApiInfoDto.getMerId());

        Integer now = DateUtil.getNowTime();
        jdTokenApi.setUpdateTime(now);
        jdTokenApiMapper.updateByIdSelective(jdTokenApi);
    }

    /**
     * 检测京东token是否合法
     * @author jitwxs
     * @date 2023/11/14 13:49
     * @param jdTokenCheckTokenDto 
     */
    public Boolean checkToken(JdTokenCheckTokenDto jdTokenCheckTokenDto){
        Boolean ckeckResult = false;

        String jd_appkeys = "6bffaadd8533473ebc24ebfce6b511dc";
        String jd_appsecrets = "e4ce34289e7d4122ae280e22acde3fd7";
        //String jd_token = "e4209eac5db9f8e20a497c06f29d22bdff5199fcc4b632f3aecb52dffdbe98be88bf369b242d5ae8";
        String jd_token = "1";
        String jdSdkUrl = "http://api.jd.com/routerjson";

        JdClient jdClient = new DefaultJdClient(jdSdkUrl, "", jd_appkeys, jd_appsecrets);
        UnionOpenOrderRowQueryRequest request = new UnionOpenOrderRowQueryRequest();
        SimpleDateFormat jdkFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTimeStr = jdkFormat.format(new Date());
        String endTimeStr = jdkFormat.format(new Date());

        OrderRowReq orderReq = new OrderRowReq();
        orderReq.setPageIndex(1);
        orderReq.setPageSize(10);
        orderReq.setStartTime(beginTimeStr);
        orderReq.setEndTime(endTimeStr);
        orderReq.setType(1);
        orderReq.setKey(jdTokenCheckTokenDto.getAuthKey());
        orderReq.setFields("goodsInfo,categoryInfo"); //筛选出参，多项逗号分隔，目前支持：categoryInfo、goodsInfo
        request.setOrderReq(orderReq);
        UnionOpenOrderRowQueryResponse response = null;
        try {
            response = jdClient.execute(request);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        if (response!=null){
            OrderRowQueryResult queryResult = response.getQueryResult();
            //授权key无权限或错误
            if(queryResult != null && queryResult.getCode() == 200){
                ckeckResult = true;
            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, queryResult.getMessage());
            }
        }

        return ckeckResult;
    }

}
